/**
 * 定时备份mysql数据库
 * */

import * as schedule from "node-schedule";
import { exec } from "child_process";
import { Logger } from "@nestjs/common";
import * as path from "path";
import * as dayjs from "dayjs";
import { EmailTool } from "src/tools/email.tool";
import { ConfigService } from "@nestjs/config";

export class BackupMysqlCommand {
  constructor(private configService: ConfigService) {
    this.initFn();
  }

  initFn() {
    const { database, username, password } = this.configService.get("DATABASE_CONFIG")[0];
    const configService = this.configService;

    // 每隔两天凌晨1点备份数据库
    schedule.scheduleJob("0 0 1 */2 * ?", function () {
      Logger.log(`数据库${database}开始备份=================>`);
      // 备份文件名
      const fileName = `${database}-${dayjs().format("YYYYMMDDHHmmss")}.sql`;
      // 备份地址
      const dumpFileName = `${path.join(__dirname, "../../public/")}/${fileName}`;
      console.log(dumpFileName);
      // 备份命令
      const dump = `mysqldump -u ${username} -p${password} ${database} > ${dumpFileName}`;

      exec(dump,async (error, stdout, stderr) => {
        if (error) return Logger.error(`数据库${database}备份失败`);
        Logger.log(`数据库${database}备份成功`);

        await new EmailTool(configService)
          .send({
            email: configService.get("EMAIL").user,
            subject: `MySQL备份`,
            text: `${database}-数据库备份成功`,
            attachments: [
              {
                filename: fileName,
                path: dumpFileName
              }
            ]
          });
      });
    });
  }
}
